package com.bobo.base.network.api;


import android.text.TextUtils;
import android.util.Log;

import com.bobo.base.AppConstants;
import com.bobo.base.BaseApplication;
import com.bobo.base.api.BaseApiService;
import com.bobo.base.network.base.UrlInterceptor;
import com.bobo.base.network.cookie.CookieJarImpl;
import com.bobo.base.network.cookie.store.PersistentCookieStore;
import com.bobo.base.network.logging.Level;
import com.bobo.base.network.logging.LoggingInterceptor;
import com.bobo.base.network.util.KLog;
import com.bobo.base.utils.MMKVUtils;
import com.bobo.base.utils.NetworkUtils;
import com.bobo.base.utils.StringUtils;
import com.bobo.base.utils.TokenUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;

import me.jessyan.retrofiturlmanager.RetrofitUrlManager;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.internal.platform.Platform;
import okio.Buffer;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 请求
 */

public class IdeaApi {
    public Retrofit retrofit;
    public OkHttpClient okHttpClient;

    public class Header implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Request.Builder builder = request.newBuilder();
            builder.addHeader("form", "android");
            if (!StringUtils.isEmpty(TokenUtils.getToken())) {
                builder.addHeader("Authorization", TokenUtils.getToken());
                if (AppConstants.isDebug)
                    Log.i("TOKEN", TokenUtils.getToken());
            }
//            builder.addHeader("version", BuildConfig.VERSION_NAME);

            if (MMKVUtils.containsKey("lng")) {
                builder.addHeader("longitude", MMKVUtils.getString("lng", ""));
                builder.addHeader("latitude", MMKVUtils.getString("lat", ""));
            }

            try {
                //省
                if (MMKVUtils.containsKey("provinceName")) {
                    builder.addHeader("province", URLEncoder.encode(MMKVUtils.getString("provinceName", ""),"UTF-8"));
                }

                //市
                if (MMKVUtils.containsKey("cityName")) {
                    builder.addHeader("city", URLEncoder.encode(MMKVUtils.getString("cityName", ""),"UTF-8"));
                }

                //区
                if (MMKVUtils.containsKey("areaContent")) {
                    builder.addHeader("area", URLEncoder.encode(MMKVUtils.getString("areaContent", ""),"UTF-8"));
                }

                //区县级 编码
                if (MMKVUtils.containsKey("areaCode") && !TextUtils.isEmpty(MMKVUtils.getString("areaCode", null))) {
                    builder.addHeader("areaCode", MMKVUtils.getString("areaCode", ""));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

//            builder.addHeader("macAddress", DeviceAttribute.getNewMac()==null?"":DeviceAttribute.getNewMac().isEmpty()?"":DeviceAttribute.getNewMac());    //设备物理地址
//            builder.addHeader("versionCode", String.valueOf(BuildConfig.VERSION_CODE));

            Request request1 = builder.build();
            return chain.proceed(request1);
        }
    }
    private IdeaApi() {

//        File cacheFile = new File(AppManager.getInstance().currentActivity().getCacheDir(), "cache");
//        Cache cache = new Cache(cacheFile, 1024 * 1024 * 100); //100Mb
//        String _time = String.valueOf(System.currentTimeMillis() / 1000);

        okHttpClient = RetrofitUrlManager.getInstance().with(new OkHttpClient.Builder())
                .readTimeout(BaseApiService.DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)
                .connectTimeout(BaseApiService.DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)
                .addNetworkInterceptor(new HttpCacheInterceptor())
                .cookieJar(new CookieJarImpl(new PersistentCookieStore(BaseApplication.getInstance().getApplicationContext())))
                .addInterceptor(new UrlInterceptor())//new BasicParamsInterceptor()//添加公共参数
                .addInterceptor(new Header())
                .addInterceptor(new LoggingInterceptor
                                .Builder()//构建者模式
//                        .loggable(BuildConfig.DEBUG) //是否开启日志打印
                                .loggable(true) //是否开启日志打印
                                .setLevel(Level.BASIC) //打印的等级
                                .log(Platform.INFO) // 打印类型
                                .request("Request") // request的Tag
                                .response("Response")// Response的Tag
//                        .addHeader("log-header", "I am the log request header.") // 添加打印头, 注意 key 和 value 都不能是中文
                                .build()
                )
//                .cache(cache)
                .build();

//        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").serializeNulls().create();
//
//        retrofit = new Retrofit.Builder()
//                .client(okHttpClient)
//                .addConverterFactory(new CustomGsonConverterFactory(gson).create())
////                .addConverterFactory(GsonConverterFactory.create(gson))
//                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
//                .baseUrl(Api.getBaseUrl())//请求接口地址
//                .build();
//        service = retrofit.create(IdeaApiService.class);
    }


    /**
     * create you ApiService
     * Create an implementation of the API endpoints defined by the {@code service} interface.
     */
    public <T> T create(final Class<T> service) {
        return create(service, AppConstants.HOST_URL);
    }

    /**
     * 物业服务器
     * @param service
     * @param <T>
     * @return
     */
    public <T> T createWY(final Class<T> service) {
        return create(service, AppConstants.HOST_URL_WY);
    }

    public <T> T create(final Class<T> service, String url) {
        if (service == null) {
            throw new RuntimeException("Api service is null!");
        }

        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").serializeNulls().create();
        retrofit = new Retrofit.Builder()
                .client(okHttpClient)
//                .addConverterFactory(new CustomGsonConverterFactory(gson).create())
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(url)//请求接口地址
                .build();
        return retrofit.create(service);
    }

    private static class SingletonHolder {
        private static IdeaApi INSTANCE = new IdeaApi();
    }

    public static IdeaApi getInstance() {
        return SingletonHolder.INSTANCE;
    }

    class HttpCacheInterceptor implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            if (!NetworkUtils.isNetworkAvailable(BaseApplication.getInstance().getApplicationContext())) {  //没网强制从缓存读取
                request = request.newBuilder()
                        .cacheControl(CacheControl.FORCE_CACHE)
                        .build();
                KLog.d("no network");
            }

            Response originalResponse = chain.proceed(request);
            if (NetworkUtils.isNetworkAvailable(BaseApplication.getInstance().getApplicationContext())) {
                //有网的时候读接口上的@Headers里的配置，你可以在这里进行统一的设置
                String cacheControl = request.cacheControl().toString();
                return originalResponse.newBuilder()
                        .header("Cache-Control", cacheControl)
                        .removeHeader("Pragma")
                        .build();
            } else {
                return originalResponse.newBuilder()
                        .header("Cache-Control", "public, only-if-cached, max-stale=2419200")
                        .removeHeader("Pragma")
                        .build();
            }
        }
    }


    private static String bodyToString(final RequestBody request) {
        try {
            final RequestBody copy = request;
            final Buffer buffer = new Buffer();
            if (copy != null)
                copy.writeTo(buffer);
            else
                return "";
            return buffer.readUtf8();
        } catch (final IOException e) {
            return "did not work";
        }
    }
}
